<template>
  <div class="scene-page">
    <Header/>
    <main class="main-content">
      <div class="content-wrapper">
        <div class="header-section">
          <h2>{{ t('scene.title') }}</h2>
          <button class="create-btn" @click="showCreateForm = true">
            {{ t('scene.create') }}
          </button>
        </div>

        <!-- 创建场景表单 -->
        <div v-if="showCreateForm" class="form-section">
          <h3>{{ t('scene.create') }}</h3>
          <form @submit.prevent="createScene">
            <div class="form-group">
              <label>{{ t('scene.name') }}:</label>
              <input v-model="newScene.name" type="text" required/>
            </div>
            <div class="form-group">
              <label>{{ t('scene.remark') }}:</label>
              <textarea v-model="newScene.remark"></textarea>
            </div>
            <div class="form-actions">
              <button type="submit">{{ t('common.save') }}</button>
              <button type="button" @click="showCreateForm = false">
                {{ t('common.cancel') }}
              </button>
            </div>
          </form>
        </div>

        <!-- 场景列表 -->
        <div v-if="scenes.length > 0" class="list-section">
          <h3>{{ t('scene.list') }}</h3>
          <div class="scene-list">
            <div
                v-for="scene in scenes"
                :key="scene.id"
                class="scene-item"
            >
              <div class="scene-info">
                <h4>{{ scene.name }}</h4>
                <p>{{ scene.remark }}</p>
                <p class="create-time">
                  {{ t('scene.createTime') }}:
                  {{ formatDate(scene.createTime) }}
                </p>
              </div>
              <div class="scene-actions">
                <button @click="editScene(scene)">
                  {{ t('common.edit') }}
                </button>
                <button @click="deleteScene(scene.id)">
                  {{ t('common.delete') }}
                </button>
                <button @click="shareScene(scene)">
                  {{ t('scene.share') }}
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 编辑场景表单 -->
        <div v-if="showEditForm" class="form-section">
          <h3>{{ t('scene.edit') }}</h3>
          <form @submit.prevent="updateScene">
            <div class="form-group">
              <label>{{ t('scene.name') }}:</label>
              <input v-model="editingScene.name" type="text" required/>
            </div>
            <div class="form-group">
              <label>{{ t('scene.remark') }}:</label>
              <textarea v-model="editingScene.remark"></textarea>
            </div>
            <div class="form-actions">
              <button type="submit">{{ t('common.save') }}</button>
              <button type="button" @click="showEditForm = false">
                {{ t('common.cancel') }}
              </button>
            </div>
          </form>
        </div>

        <!-- 分享场景表单 -->
        <div v-if="showShareForm" class="form-section">
          <h3>{{ t('scene.share') }}</h3>
          <form @submit.prevent="submitShare">
            <div class="form-group">
              <label>{{ t('scene.share.isPublic') }}:</label>
              <select v-model="shareData.isPublic">
                <option :value="1">{{ t('common.yes') }}</option>
                <option :value="0">{{ t('common.no') }}</option>
              </select>
            </div>
            <div class="form-group">
              <label>{{ t('scene.share.expireTime') }}:</label>
              <input v-model="shareData.expireTime" type="datetime-local"/>
            </div>
            <div class="form-actions">
              <button type="submit">{{ t('common.save') }}</button>
              <button type="button" @click="showShareForm = false">
                {{ t('common.cancel') }}
              </button>
            </div>
          </form>
        </div>

        <!-- 分享列表 -->
        <div v-if="shares.length > 0" class="list-section">
          <h3>{{ t('scene.share.list') }}</h3>
          <div class="share-list">
            <div
                v-for="share in shares"
                :key="share.id"
                class="share-item"
            >
              <div class="share-info">
                <p>{{ t('scene.share.isPublic') }}:
                  {{ share.isPublic ? t('common.yes') : t('common.no') }}
                </p>
                <p>{{ t('scene.share.createTime') }}:
                  {{ formatDate(share.createTime) }}
                </p>
                <p v-if="share.expireTime">{{ t('scene.share.expireTime') }}:
                  {{ formatDate(share.expireTime) }}
                </p>
              </div>
              <div class="share-actions">
                <button @click="deleteShare(share.id)">
                  {{ t('common.delete') }}
                </button>
              </div>
            </div>
          </div>
        </div>

        <div v-if="scenes.length === 0 && !showCreateForm" class="empty-state">
          <p>{{ t('scene.noScenes') }}</p>
          <button @click="showCreateForm = true">
            {{ t('scene.createFirst') }}
          </button>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import Header from '../components/Header.vue'
import {sceneService} from '../services/sceneService'

export default {
  name: 'ScenePage',
  components: {
    Header
  },
  data() {
    return {
      scenes: [],
      shares: [],
      showCreateForm: false,
      showEditForm: false,
      showShareForm: false,
      newScene: {
        name: '',
        remark: ''
      },
      editingScene: {
        id: null,
        name: '',
        remark: ''
      },
      shareData: {
        sceneId: null,
        isPublic: 1,
        expireTime: ''
      },
      currentScene: null
    }
  },
  mounted() {
    this.loadScenes()
    this.loadShares()
  },
  methods: {
    t(key) {
      return this.$t(key)
    },

    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString()
    },

    async loadScenes() {
      try {
        const response = await sceneService.listScenes()
        this.scenes = response.data || response
      } catch (error) {
        console.error('Failed to load scenes:', error)
      }
    },

    async loadShares() {
      try {
        const response = await sceneService.listShares()
        this.shares = response.data || response
      } catch (error) {
        console.error('Failed to load shares:', error)
      }
    },

    async createScene() {
      try {
        const response = await sceneService.createScene(this.newScene)
        if (response.data || response === true) {
          this.$message?.success(this.t('scene.createSuccess') || '场景创建成功')
          this.showCreateForm = false
          this.newScene = {name: '', remark: ''}
          this.loadScenes()
        }
      } catch (error) {
        console.error('Failed to create scene:', error)
        this.$message?.error(this.t('scene.createFailed') || '场景创建失败')
      }
    },

    editScene(scene) {
      this.editingScene = {...scene}
      this.showEditForm = true
    },

    async updateScene() {
      try {
        const response = await sceneService.updateScene(this.editingScene)
        if (response.data || response === true) {
          this.$message?.success(this.t('scene.updateSuccess') || '场景更新成功')
          this.showEditForm = false
          this.loadScenes()
        }
      } catch (error) {
        console.error('Failed to update scene:', error)
        this.$message?.error(this.t('scene.updateFailed') || '场景更新失败')
      }
    },

    async deleteScene(id) {
      if (!confirm(this.t('scene.confirmDelete') || '确定要删除这个场景吗？')) {
        return
      }

      try {
        const response = await sceneService.deleteScene(id)
        if (response.data || response === true) {
          this.$message?.success(this.t('scene.deleteSuccess') || '场景删除成功')
          this.loadScenes()
        }
      } catch (error) {
        console.error('Failed to delete scene:', error)
        this.$message?.error(this.t('scene.deleteFailed') || '场景删除失败')
      }
    },

    shareScene(scene) {
      this.currentScene = scene
      this.shareData.sceneId = scene.id
      this.shareData.isPublic = 1
      this.shareData.expireTime = ''
      this.showShareForm = true
    },

    async submitShare() {
      try {
        const response = await sceneService.shareScene(this.shareData)
        if (response.data || response === true) {
          this.$message?.success(this.t('scene.share.success') || '场景分享成功')
          this.showShareForm = false
          this.loadShares()
        }
      } catch (error) {
        console.error('Failed to share scene:', error)
        this.$message?.error(this.t('scene.share.failed') || '场景分享失败')
      }
    },

    async deleteShare(id) {
      if (!confirm(this.t('scene.share.confirmDelete') || '确定要删除这个分享吗？')) {
        return
      }

      try {
        const response = await sceneService.deleteShare(id)
        if (response.data || response === true) {
          this.$message?.success(this.t('scene.share.deleteSuccess') || '分享删除成功')
          this.loadShares()
        }
      } catch (error) {
        console.error('Failed to delete share:', error)
        this.$message?.error(this.t('scene.share.deleteFailed') || '分享删除失败')
      }
    }
  }
}
</script>

<style scoped>
.scene-page {
  padding-top: 60px;
  min-height: 100vh;
}

.main-content {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.content-wrapper {
  background-color: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  max-width: 1200px;
  margin: 0 auto;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.create-btn {
  background-color: #1890ff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.create-btn:hover {
  background-color: #40a9ff;
}

h2 {
  color: #1890ff;
  margin-bottom: 16px;
}

h3 {
  color: #1890ff;
  margin-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 8px;
}

h4 {
  margin: 0 0 8px 0;
  color: #333;
}

.form-section {
  background-color: #fafafa;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 24px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 4px;
  font-weight: bold;
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  min-height: 80px;
  resize: vertical;
}

.form-actions {
  display: flex;
  gap: 10px;
}

.form-actions button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.form-actions button[type="submit"] {
  background-color: #52c41a;
  color: white;
}

.form-actions button[type="button"] {
  background-color: #d9d9d9;
  color: #333;
}

.scene-list,
.share-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.scene-item,
.share-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.scene-info,
.share-info {
  flex: 1;
}

.scene-info p,
.share-info p {
  margin: 4px 0;
  color: #666;
}

.create-time {
  font-size: 12px;
  color: #999;
}

.scene-actions,
.share-actions {
  display: flex;
  gap: 8px;
}

.scene-actions button,
.share-actions button {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.scene-actions button:first-child,
.share-actions button:first-child {
  background-color: #1890ff;
  color: white;
}

.scene-actions button:nth-child(2) {
  background-color: #ff4d4f;
  color: white;
}

.scene-actions button:nth-child(3) {
  background-color: #52c41a;
  color: white;
}

.share-actions button:first-child {
  background-color: #ff4d4f;
  color: white;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.empty-state p {
  font-size: 16px;
  color: #999;
  margin-bottom: 16px;
}

.empty-state button {
  background-color: #1890ff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

@media (max-width: 768px) {
  .scene-item,
  .share-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .scene-actions,
  .share-actions {
    align-self: flex-end;
  }

  .header-section {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
}
</style>